const CryptoJS = require('crypto-js');

export const BASE_NAME = '动态漫' //小程序名称
export const BASE_URL = 'http://anime.api.test.kdxgs.com/api/' //域名
export const COMPANY = '杭州瑶池文化传播有限公司' //公司名称 
export const EMAIL = 'read@cqyaochi.com' //邮箱

export const prigramId = '1' //小程序id 
export const AccessKey = 'BVKIypntEsxraSwok5MNmW6J' //公钥
export const SecretKey = 'LwRg4cIaxj8zr0m36Jeodv1ynX7bhql5FWEQBMAK' //密钥

// 生成随机数
export function generateRandomNumber() {
	const timestamp = Date.now().toString();
	const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
	let randomPart = '';
	for (let i = 0; i < 32 - timestamp.length; i++) {
		randomPart += characters[Math.floor(Math.random() * characters.length)];
	}
	return timestamp + randomPart;
}

// 接口参数拼接
export function convertDataToString(data) {
	if (typeof data !== 'object' || data === null) {
		return '';
	}
	const flatObject = {};
	const specialArrayFields = ['ids', 'comic_ids']; // 定义需要特殊处理的字段名数组 书架删除和播放记录删除
	function flatten(obj) {
		for (const key in obj) {
			if (obj.hasOwnProperty(key)) {
				const value = obj[key];
				if (value && typeof value === 'object' && !Array.isArray(value)) {
					flatten(value);
				} else if (Array.isArray(value)) {
					if (specialArrayFields.includes(key)) {
						if (value.length === 1) {
							flatObject[key] = `[${value[0]}]`;
						} else if (value.length > 1) {
							flatObject[key] = `[${value.join(',')}]`;
						}
					} else {
						value.forEach((item, index) => {
							if (typeof item === 'object' && item !== null) {
								flatten(item);
							} else {
								flatObject[`${key}[${index}]`] = item;
							}
						});
					}
				} else {
					flatObject[key] = value;
				}
			}
		}
	}
	flatten(data);
	const sortedKeys = Object.keys(flatObject).sort();
	const parts = sortedKeys.map(key => {
		let value = flatObject[key];
		if (specialArrayFields.includes(key) && (value.startsWith('[') && value.endsWith(']'))) {
			return `${key}=${value}`;
		}
		// return `${key}=${encodeURIComponent(value)}`;
		return `${key}=${value}`;
	});
	return parts.join('&');
}

// 签名生成
export function createSignature(params) {
	let md5Hash = CryptoJS.MD5(params).toString().toUpperCase(); // MD5 加密并转大写
	//2. sha1 加密
	let sha1Hash = CryptoJS.SHA1(md5Hash).toString()
	return sha1Hash
}